package com.fast.develop.meta.base.reader;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.fast.develop.meta.base.Meta;
import com.fast.develop.meta.base.resource.MultResource;
import com.fast.develop.meta.base.loader.MetaLoader;
import com.fast.develop.meta.base.resource.PathResource;
import com.fast.develop.meta.base.source.MetaSources;
import lombok.extern.slf4j.Slf4j;
import org.everit.json.schema.ValidationException;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 莫寅
 * @createTime 2022-06-07 18:23
 * @desc：
 */
@Slf4j
public class SchemaFileReader implements SchemaReader{

    private MetaSources metaSources;

    private List<InputStream> schemas = new ArrayList<>();

    /**
     * 读取文件地址
     */
    private MultResource<PathResource> resources;

    private MetaLoader metaLoader;



    public SchemaFileReader(MultResource<PathResource> resources, MetaLoader metaLoader) {
        this.metaSources = new MetaSources();
        this.resources = resources;
        this.metaLoader = metaLoader;
    }

    @Override
    public List<Meta> read(){
        List<String> folders = metaSources.getSchemaFolderPaths();
        if(folders.isEmpty()){
            read(resources);
        }
//        else{
//            folders.forEach(s -> {
//                read(s);
//            });
//        }


        List<InputStream> jsonInputStreams = schemas;

        List<Meta> metas = new ArrayList<>();
        jsonInputStreams.forEach(inputStream -> {
            String strSchema = IoUtil.readUtf8(inputStream);
            JSONObject rawSchema = null;
            try{
                rawSchema = new JSONObject(new JSONTokener(strSchema));

                Boolean enabled = rawSchema.optBoolean("enabled");
                if(enabled){
                    Meta meta = metaLoader.load(rawSchema);
                    metas.add(meta);

                    if(log.isDebugEnabled()){
                        String name = rawSchema.optString("name");
                        if(StrUtil.isNotBlank(name)){
                            log.debug("成功读取模型：{}", rawSchema.optString("name"));
                        }
                    }
                }
            }catch (ValidationException validationException){
                log.warn("模型不满足加载规范：{}  --> 模型数据：{}", validationException.getMessage(), rawSchema);
            }
            catch (JSONException jsonException){
                log.error("模型不满足加载规范：{}", strSchema, jsonException);
                throw jsonException;
            }

        });

        return metas;
    }

    @Override
    public void validation(JSONObject rawSchema) {
        metaLoader.validation(rawSchema);
    }


    private void read(MultResource<PathResource> resources){
        schemas.addAll(metaSources.getJsonInputStreams());
        schemas.addAll(resources.getInputStreams());
    }

//    private void read(String path){
//        List<File> files = FileUtil.loopFiles(path, new FileFilter() {
//            @Override
//            public boolean accept(File pathname) {
//                if(pathname.getName().indexOf(".json") != -1){
//                    return true;
//                }
//                return false;
//            }
//        });
//
//        List<Resource> fileInputStreams = files.stream().map(file -> {
//            try {
//                return new InputStreamResource(new FileInputStream(file));
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//            return null;
//        }).collect(Collectors.toList());
//
//
//    }



    public List<InputStream> getSchemas() {
        return schemas;
    }
}
